const express = require(`express`)
const router = express.Router()
const mongoose = require('mongoose');
const trans = require('./myglobal').trans;

router.get('/api/v1/beginTransaction', async (req, res, next) => {
    if (trans[req.sessionID])
        delete trans[req.sessionID]
    var mysession = await mongoose.startSession()

    await mysession.startTransaction();
    trans[req.sessionID] = mysession;
    console.log("sessionID " + req.sessionID);
    res.jsonp({ data: '' });

})
router.get('/api/v1/commitTransaction', async (req, res, next) => {
    if (trans[req.sessionID]) {
        var session = trans[req.sessionID];
        if (session.inTransaction()) {
            await session.commitTransaction();
            
            res.jsonp({ data: '' });
        } else {
            delete trans[req.sessionID]
            res.status(500).send("transaction not begin");
        }
    } else {
        res.status(500).send("no transaction");
    }
})
router.get('/api/v1/abortTransaction', async (req, res, next) => {
    //
    if (trans[req.sessionID]) {
        var session = trans[req.sessionID];
        if (session.inTransaction()) {
            await session.abortTransaction();

            res.jsonp({ data: '' });
            delete trans[req.sessionID];
        } else {
            delete trans[req.sessionID];
            res.jsonp({ data: '' });
        }
    } else {
        res.status(500).send("no transaction");
    }

    //
})
router.get('/api/v1/endTransaction', async (req, res, next) => {
    //
    if (trans[req.sessionID]) {

        var session = trans[req.sessionID];
        if (session.inTransaction()) {
            await session.endSession();
            delete trans[req.sessionID];
            res.jsonp({ data: '' });
        } else {
            delete trans[req.sessionID];
            res.jsonp({ data: '' });
        }
    } else {
        res.status(500).send("no transaction");
    }

    //
})

module.exports = router
